package android.apps.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.apps.R;
import android.apps.adapter.AlbumItemAdapter;
import android.apps.adapter.AlbumItemAdapter1;
import android.apps.adapter.AlbumItemAdapter2;
import android.apps.bean.ComparatorAddr;
import android.apps.bean.MadeListItem;
import android.apps.bean.MadeListItem2;
import android.apps.bean.PhotoUpImageBucket;
import android.apps.bean.PhotoUpImageItem;
import android.apps.database.DBManager;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.SDKInitializer;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

//整合直接是进入这个；
//这里面要用list嵌套gridview实现；
public class AlbumItemActivity extends Activity implements OnClickListener {

    private ListView listView;
    private TextView back, ok, swap;
    private PhotoUpImageBucket photoUpImageBucket;
    private ArrayList<PhotoUpImageItem> selectImages;
    private AlbumItemAdapter adapter;
    private List<PhotoUpImageItem> imageList;//这是原始的list；按时间排序，保留；
    private List<PhotoUpImageItem> imageListCopy = new ArrayList<PhotoUpImageItem>();//这是copy的list；按地点排序；

    private List<MadeListItem> madeList_addr = new ArrayList<MadeListItem>();

    private List<MadeListItem2> madeList_time = new ArrayList<MadeListItem2>();

    private String itemType = "";
    private boolean isShowAdrr = true;
    private AlbumItemAdapter2 adapter_addr;
    private AlbumItemAdapter1 adapter_time;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
//            adapter = new AlbumItemAdapter(imageList, AlbumItemActivity.this);
            if (dialog != null && dialog.isShowing())
                dialog.dismiss();
            adapter_addr = new AlbumItemAdapter2(madeList_addr, AlbumItemActivity.this);
            listView.setAdapter(adapter_addr);
        }
    };
    private ProgressDialog dialog;
    private DBManager dbManager;


    /**
     * 把 imageList 切成n个list；根据当中的address；
     */
    private void makeList() {
        //按时间；
        itemType = imageList.get(0).getDatatime();//第一个标签
        List<PhotoUpImageItem> listTime = new ArrayList<PhotoUpImageItem>();//第2个列表
        Log.e("LCY", "初始imasdf2=" + listTime);
        for (int i = 0; i < imageList.size(); i++) {
            if (imageList.get(i).getDatatime().equals(itemType)) {
                listTime.add(imageList.get(i));
                Log.e("LCY", "相同时间标签=" + itemType);
                if (i == imageList.size() - 1) {
                    madeList_time.add(new MadeListItem2(listTime, itemType));
                }
            } else {
                madeList_time.add(new MadeListItem2(listTime, itemType));
                itemType = imageList.get(i).getDatatime();//下一个标签
                listTime = new ArrayList<PhotoUpImageItem>();//下一个列表
                listTime.add(imageList.get(i));
                if (i==imageList.size()-1){
                    madeList_time.add(new MadeListItem2(listTime, itemType));
                }
                Log.e("LCY", "新的时间标签=" + itemType);
            }
        }
        for (int i = 0; i < madeList_time.size(); i++)
            Log.e("LCY", "zong时间标签=" + madeList_time.get(i).getItemTypeTime());
//        按地点
        itemType = imageListCopy.get(0).getAddress();//第一个标签
        List<PhotoUpImageItem> listAddr = new ArrayList<PhotoUpImageItem>();//第一个列表

        for (int i = 0; i < imageList.size(); i++) {
            Log.e("LCy", "i=" + i);
            String x = (imageListCopy.get(i).getAddress() == null ? "" : imageListCopy.get(i).getAddress());
            Log.e("LCY", "地址标签=" + x);
            if (itemType.equals(x)) {
                listAddr.add(imageListCopy.get(i));
                if (i == imageList.size() - 1) {
                    madeList_addr.add(new MadeListItem(listAddr, itemType));
                }
            } else {
                madeList_addr.add(new MadeListItem(listAddr, itemType));
                itemType = imageListCopy.get(i).getAddress();//下一个标签
                listAddr = new ArrayList<PhotoUpImageItem>();//下一个列表
                listAddr.add(imageListCopy.get(i));
                if (i == imageListCopy.size() - 1) {
                    madeList_addr.add(new MadeListItem(listAddr, itemType));
                }
            }
        }
        for (int i = 0; i < madeList_addr.size(); i++)
            Log.e("LCY", "zong地址标签=" + madeList_addr.get(i).getItemTypeAddr());
        mHandler.sendEmptyMessage(1);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.album_item_images);
        init();
        setListener();
    }

    private void init() {
        listView = (ListView) findViewById(R.id.album_item_gridv);
        back = (TextView) findViewById(R.id.back);
        ok = (TextView) findViewById(R.id.sure);
        swap = (TextView) findViewById(R.id.swap);
        swap.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!isShowAdrr) {
//                    adapter = new AlbumItemAdapter(imageListCopy, AlbumItemActivity.this);
//                    listView.setAdapter(adapter);
                    if (adapter_addr == null)
                        adapter_addr = new AlbumItemAdapter2(madeList_addr, AlbumItemActivity.this);
                    listView.setAdapter(adapter_addr);
                    isShowAdrr = true;
                } else {
//                    adapter = new AlbumItemAdapter(imageList, AlbumItemActivity.this);
//                    listView.setAdapter(adapter);
                    if (adapter_time == null)
                        adapter_time = new AlbumItemAdapter1(madeList_time, AlbumItemActivity.this);
                    listView.setAdapter(adapter_time);
                    isShowAdrr = false;
                }
            }
        });
        selectImages = new ArrayList<PhotoUpImageItem>();

//        Intent intent = getIntent();
//        photoUpImageBucket = (PhotoUpImageBucket) intent.getSerializableExtra("imagelist");
//        imageList = photoUpImageBucket.getImageList();

        initDatabase();

        imageList = dbManager.searchAllData();
        for (PhotoUpImageItem item : imageList) {
            Log.e("LCy", "查询得到ImageId=" + item.getImageId() + ",path=" + item.getImagePath() + ",时间=" + item.getDatatime() + ",地名为==" + item.getAddress() + ",最高温=" + item.getMaxTemp() + ",最低温=" + item.getMinTemp());
        }
        if (imageList.size() > 0)
            sortListByAddr();
    }

    /**
     * 模拟初始化数据库；实际为拍摄照片保存时执行！！
     */
    private void initDatabase() {
        PhotoUpImageItem photoUpImageItem11 = new PhotoUpImageItem(1 + "", "/storage/emulated/0/Yado/camerajpg/C360_2015-11-13-19-35-14-315.jpg", "2015-11-13", "上海...", 54.23, 1.12);
        PhotoUpImageItem photoUpImageItem22 = new PhotoUpImageItem(2 + "", "/storage/emulated/0/Yado/camerajpg/C360_2015-11-13-19-35-18-400.jpg", "2015-11-13", "北京...", 75.23, 7.12);
        PhotoUpImageItem photoUpImageItem33 = new PhotoUpImageItem(3 + "", "/storage/emulated/0/Yado/camerajpg/C360_2015-11-20-09-09-16-110.jpg", "2015-11-20", "上海...", 49.23, 2.72);
        PhotoUpImageItem photoUpImageItem44 = new PhotoUpImageItem(4 + "", "/storage/emulated/0/Yado/camerajpg/C360_2015-12-11-20-13-14-127.jpg", "2015-12-11", "上海...", 77.23, 5.19);
        PhotoUpImageItem photoUpImageItem55 = new PhotoUpImageItem(4 + "", "/storage/emulated/0/Yado/camerajpg/VID_20160102_143734.mp4", "2016-01-02", "北京...", 47.23, 3.76);
        dbManager = new DBManager(this);
        List<PhotoUpImageItem> list = new ArrayList<PhotoUpImageItem>();
        list.add(photoUpImageItem11);
        list.add(photoUpImageItem22);
        list.add(photoUpImageItem33);
        list.add(photoUpImageItem44);
        list.add(photoUpImageItem55);
        for (int i = 0; i < list.size(); i++) {
            Log.e("LCy", "存储的时间" + list.get(i).getDatatime());
        }
        dbManager.clearData();
        dbManager.add(list);
    }

    /**
     * 按时间排序；
     */
//    private void sortListByTime() {
//        ComparatorTime comparator = new ComparatorTime();
//        Collections.sort(imageList, comparator);//按时间排序；
//        for (int i = 0; i < imageList.size(); i++) {
//            PhotoUpImageItem photo = imageList.get(i);
//            Log.e("LCY", photo.getAddress() + "," + photo.getDatatime());
//        }
//        //排序完成；
//    }

    /**
     * 在分线程；
     * 按地点排序；
     */
    private void sortListByAddr() {
        dialog = new ProgressDialog(this);
        dialog.setMessage("加载中...");
        dialog.show();
        imageListCopy = new ArrayList<PhotoUpImageItem>(imageList);
        new Thread(new Runnable() {
            @Override
            public void run() {
//                for (int i = 0; i < imageListCopy.size(); i++) {
//                    try {
//                        PhotoUpImageItem photoUpImageItem = imageListCopy.get(i);
//                        ExifInterface exif = new ExifInterface(photoUpImageItem.getImagePath());
//                        String latitude_str = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE);// 纬度
//                        String longitude_str = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);//经度；
//                        String datetime = exif.getAttribute(ExifInterface.TAG_DATETIME);
//                        if (datetime != null && datetime.length() >= 10) {
//                            Log.e("LCY", "拍摄时间=" + datetime.substring(0, 10));
//                            photoUpImageItem.setDatatime(datetime.substring(0, 10));
//                        }
////                设置地名；
////                把地名放进去；
////                1按地名排序；对应的就是首字母；2.按时间；
////                按首字母展示，item为gridview；
//                        if (longitude_str != null && latitude_str != null) {
//                            String[] longitude2 = longitude_str.split(",");
//                            String[] latitude2 = latitude_str.split(",");
//                            double realLongitude = changeTo(longitude2[0], longitude2[1], longitude2[2]);
//                            double realLatitude = changeTo(latitude2[0], latitude2[1], latitude2[2]);
//                            Geocoder geocoder = new Geocoder(AlbumItemActivity.this);
//                            List<Address> x1 = geocoder.getFromLocation(realLatitude, realLongitude, 1);
//                            Log.e("LCY", "地理名字=" + x1.get(0).getAddressLine(0));
//                            photoUpImageItem.setAddress(x1.get(0).getAddressLine(0));
//                        } else {
//                            photoUpImageItem.setAddress("");
//                        }
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }
                ComparatorAddr comparator = new ComparatorAddr();
                Collections.sort(imageListCopy, comparator);//按地点排序；
                for (int i = 0; i < imageListCopy.size(); i++) {
                    PhotoUpImageItem photo = imageListCopy.get(i);
                    Log.e("LCY", photo.getAddress() + "," + photo.getDatatime());
                }
                //排序完成；
                Log.e("LCY", "按地点排序完成");
                for (int i = 0; i < imageListCopy.size(); i++) {
                    PhotoUpImageItem photo = imageListCopy.get(i);
                    Log.e("LCY", "地点顺序=" + photo.getAddress());
                }
                makeList();
            }
        }).start();
    }

    private double changeTo(String s, String s1, String s2) {
        double l1 = partDouble(s);
        double l2 = partDouble(s1);
        double l3 = partDouble(s2);
        double realNum = l1 + l2 / 60 + l3 / 3600;
        return realNum;
    }

    private double partDouble(String s) {
        String[] ss = s.split("/");
        int xxx = Integer.parseInt(ss[0]);
        int xxx2 = Integer.parseInt(ss[1]);
        double y = 1.0 * xxx / xxx2;
        return y;
    }

    private void setListener() {
        back.setOnClickListener(this);
        ok.setOnClickListener(this);
        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                CheckBox checkBox = (CheckBox) view.findViewById(R.id.check);
                photoUpImageBucket.getImageList().get(position).setSelected(
                        !checkBox.isChecked());
                adapter.notifyDataSetChanged();
                Toast.makeText(AlbumItemActivity.this, "相册的postion=" + position,
                        Toast.LENGTH_SHORT).show();
//				photoUpImageBucket.getImageList().get(position).setSelected(
//						!photoUpImageBucket.getImageList().get(position).isSelected());
//				adapter.notifyDataSetChanged();
                if (photoUpImageBucket.getImageList().get(position).isSelected()) {
                    if (selectImages.contains(photoUpImageBucket.getImageList().get(position))) {

                    } else {
                        selectImages.add(photoUpImageBucket.getImageList().get(position));
                    }
                } else {
                    if (selectImages.contains(photoUpImageBucket.getImageList().get(position))) {
                        selectImages.remove(photoUpImageBucket.getImageList().get(position));
                    } else {

                    }
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.sure:
                Intent intent = new Intent(AlbumItemActivity.this, SelectedImagesActivity.class);
                intent.putExtra("selectIma", selectImages);
                startActivity(intent);
                break;

            default:
                break;
        }
    }

}
